package com.minesweeper;

import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class RecordsView {
    private Stage primaryStage;

    public RecordsView(Stage primaryStage) {
        this.primaryStage = primaryStage;
    }

    public void show() {
        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(10));

        Label title = new Label("最近 30 次游戏记录");

        ScrollPane scrollPane = new ScrollPane();
        VBox recordsBox = new VBox(5);
        recordsBox.setPadding(new Insets(10));

        try (Connection conn = DriverManager.getConnection(DatabaseManager.DB_URL, DatabaseManager.DB_USER, DatabaseManager.DB_PASSWORD)) {
            String sql = "SELECT difficulty, elapsed_seconds, is_win, timestamp FROM game_records ORDER BY timestamp DESC LIMIT 30";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                String difficulty = rs.getString("difficulty");
                int elapsedSeconds = rs.getInt("elapsed_seconds");
                boolean isWin = rs.getBoolean("is_win");
                String timestamp = rs.getTimestamp("timestamp").toString();

                String result = isWin ? "胜利" : "失败";
                Label recordLabel = new Label("难度: " + difficulty + " | 用时: " + elapsedSeconds + " 秒 | 结果: " + result + " | 时间: " + timestamp);
                recordsBox.getChildren().add(recordLabel);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        scrollPane.setContent(recordsBox);

        Button backButton = new Button("返回主菜单");
        backButton.setOnAction(e -> {
            MainMenu mainMenu = new MainMenu(primaryStage);
            mainMenu.show();
        });

        vbox.getChildren().addAll(title, scrollPane, backButton);

        Scene scene = new Scene(vbox, 400, 300);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}